<?php

namespace common\models\course;

use Yii;
use common\helpers\ArrayHelper;
use common\helpers\StringHelper;

/**
 * This is the model class for table "{{%course_category}}".
 *
 * @property int $id
 * @property string $number 分类编号
 * @property string $name 分类名称
 * @property int $parent_id 父类ID
 * @property string $icon 分类图标
 * @property int $listorder 排序值
 * @property int $degree 节点出度
 * @property int $status 状态
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 */
class CourseCategory extends \common\base\ActiveRecord {

    const STATUS_ACTIVE = 10;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%course_category}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['number'], 'required'],
            [['parent_id', 'listorder', 'degree', 'status', 'created_at', 'updated_at'], 'integer'],
            [['number'], 'string', 'max' => 32],
            [['name'], 'string', 'max' => 64],
            [['icon'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'number' => '分类编号',
            'name' => '分类名称',
            'parent_id' => '父类ID',
            'icon' => '分类图标',
            'listorder' => '排序值',
            'degree' => '节点出度',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    public function getRecommendCourse() {
        
    }

    /**
     * 将数组转换成树形结构
     */
    public static function getCategoryTree() {

        $data = static::find()
        ->select(['id', 'name', 'parent_id'])
        ->where([
            'status' => self::STATUS_ACTIVE
        ])
        ->asArray()
        ->all();

        if (empty($data)) {
            return $data;
        }

        return self::formatCategoryTree($data);
    }

    /**
     * 将数组转换成树形结构
     */
    protected static function formatCategoryTree($tree, $pkey = 0, $keyname = 'id', $pkname = 'parent_id', $childname = 'children') {
        $return = [];
        foreach ($tree as $key => $leaf) {
            $id = ArrayHelper::getValue($leaf, $keyname);
            $pid = ArrayHelper::getValue($leaf, $pkname);
            if (0 == $pkey) {
                ArrayHelper::setValue($leaf, $childname, []);
            }
            if ($pid != $pkey) {
                continue;
            }

            ArrayHelper::remove($tree, $key);
            foreach ($tree as $temp) {
                if ($temp[$pkname] == $id) {
                    $child = self::formatCategoryTree($tree, $id, $keyname, $pkname, $childname);
                    ArrayHelper::setValue($leaf, $childname, $child);
                    break;
                }
            }



            $return[] = $leaf;
        }
        return $return;
    }

    protected static function formatCategoryItem($leaf) {
        $level = $leaf['level'];

        ArrayHelper::remove($leaf, 'parent_id');
        ArrayHelper::remove($leaf, 'channel_id');
        $link = ArrayHelper::remove($leaf, 'link');

        if ($level == 1) {
            if (empty($leaf['spread'])) {
                ArrayHelper::setValue($leaf, 'spread', [
                    'title' => $leaf['name'],
                    'description' => $leaf['name'],
                    'image' => $leaf['image'],
                    'link' => '',
                    'bgcolor' => '#FF6600',
                    'rgb' => StringHelper::hex2rgb('#FF6600'),
                ]);
            } else {
                unset($leaf['spread']['id']);
                unset($leaf['spread']['category_id']);
                unset($leaf['spread']['listorder']);
                unset($leaf['spread']['status']);
                unset($leaf['spread']['created_at']);
                unset($leaf['spread']['updated_at']);
            }
        } else {
            ArrayHelper::remove($leaf, 'spread');
        }

        if ($level == 2) {
            $childname = 'children';
            $children = ArrayHelper::getValue($leaf, $childname, []);
            if (empty($children)) {
                $children = [
                    [
                        "id" => "51",
                        "name" => "定位电话",
                        "level" => "3",
                        "image" => '',
                        "link" => '',
                        "type" => 'goods',
                    ],
                ];
                ArrayHelper::setValue($leaf, $childname, $children);
            }
            if (!empty($leaf['channel'])) {
                $channel = $leaf['channel'];
                $leaf['channel'] = [
                    'name' => '进入' . $channel['name'] . '频道 >',
                    'link' => $channel['link'],
                ];
            }
        } else {
            ArrayHelper::remove($leaf, 'channel');
        }

        if ($level == 3) {
            $type = 'category';
            if ($link) {
                $type = 'link';
            } else {
                $link = '';
            }
            ArrayHelper::setValue($leaf, 'link', $link);
            ArrayHelper::setValue($leaf, 'type', $type);
        } else {
            ArrayHelper::remove($leaf, 'image');
        }

        return $leaf;
    }

    protected static function updateLevel($max = 3) {
        $parentids = 0;
        for ($i = 0; $i < $max; $i++) {
            $level = $i + 1;
            static::updateAll(['level' => $level], ['parent_id' => $parentids]);
            $parentids = static::find()->where(['level' => $level])->column();
        }
    }

}
